$(document).ready(function() {
	/*Invitesq.mapTemplate = function() {
		return '' + '<div class="span9">' + 
		'<div id="map-canvas" class="span6" style="height:500px"></div>' + 
		'<div class="span2"><h1>Event Info<h1></div>' + 
		'<br/>' + 
		'<input class="span2" type="text" placeholder="Address" id="address" />' + 
		'</div>';
	};*/
	
	Invitesq.LocationModel = Backbone.Model.extend ({
		defaults: {
			address: "",
			title: "",
			country: "",
			city: "",
			postal_code: "",
			latitude: "",
			longitude: "",	
		}
	});

	Invitesq.mapSideTemplate = function() {
		return '' + '<div class="span12"><h2>Location<h2></div>' + 
		'<br/>' + 
		'<div id="map-canvas" class="span12"></div>' + 
		'<br/>' + 
		
		'<div id="location-search" class="span12" style="display:none">'  +
			'<div class="span10">'  +
				'<input class="span12" type="text" placeholder="Address" id="address" />' +
			'</div>' +
			'<div id="location-add-btn" class="span2"></div>' + 
		'</div>' + 
		'<br/>' + 
		'<div class="span9" id="event-location"></div>' ;
	};
	
	Invitesq.mapLocationTemplate = function() {
		return '' + 
		'<div><h4 class = "event-sub-title"><%= title %><h4></div>' + 
		'<p class = "event-sub-address"><%= address %></p>'+
		'<p class = "event-sub-city"><%= city %></p>'+
		'<p class = "event-sub-country"><%= country %> <%= postal_code %></p>';
	};
	
	Invitesq.LocationCollection = Backbone.Collection.extend({
		model: Invitesq.LocationModel
	});
	
	Invitesq.locationCollection = new Invitesq.LocationCollection();
	
	Invitesq.LocationView = Backbone.View.extend({
		
		template : _.template(Invitesq.mapLocationTemplate()),
		
		initialize: function() {
			_.bindAll(this,'render','setTitle');
		},
		
		events: {
			"blur .event-sub-title": "setTitle"
		},
		
		setTitle: function() {
			console.log("set title" + this.$('.event-sub-title').html());
			this.model.set({title : this.$('.event-sub-title').html()});
		},
		
		render: function() {
			$(this.el).html(this.template(this.model.toJSON()));
			return this;
		} 
		
	});
	
	Invitesq.MapSideView = Backbone.View.extend({
		tagName : "div",
		
		className : "row-fluid",
		
		template : _.template(Invitesq.mapSideTemplate()),
		
		editable: false,

		addresses : ["Singapore Marina Bay Sands"],
		
		titles : ["Main Location"],

		initialize : function() {
			_.bindAll(this, 'render', 'initMap', 'getAddress','addMarker', 'createLocationModel', 'enableEdit' , 'disableEdit','collectionChanged','appendLocation');
			
			// Location collection
			Invitesq.locationCollection.on("add", this.collectionChanged, this);
			
			this.render();
			this.initMap();
		},

		initMap : function() {
			Invitesq.geocoder = new google.maps.Geocoder();
			var myOptions = {
				center : new google.maps.LatLng(1.3, 103.8),
				zoom : 11,
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
			this.map = new google.maps.Map(this.$('#map-canvas').get(0), myOptions);
			
			// Set marker at the default value
			// this.addMarker(this.addresses[0], this.titles[0]);
			
		},

		getAddress : function(e) {
			if(e.keyCode != 13) {
				return;
			}
			var address = document.getElementById("address").value;
			this.addMarker(address,this.titles[0]);
		},
		
		btnAddress : function() {
			var address = document.getElementById("address").value;
			this.addMarker(address,this.titles[0]);
		},
		
		createLocationModel: function(geoResult) {
			var postal_code = country = city = "";
			
			// Obtain all location and store in location model 
			_.each(geoResult.address_components, function (ac) { 
				
				if (ac.types[0] == 'postal_code') 
				{
					postal_code = ac.short_name;
				}
				else if (ac.types[0] == 'country') 
				{
					country = ac.long_name;
				}
				else if (ac.types[0] == 'locality') 
				{
					city = ac.short_name;
				} 
			});
			// Use default title
			title = this.titles[0];
			var locationModel = new Invitesq.LocationModel ({
				address : geoResult.formatted_address, 
				latitude: geoResult.geometry.location.lat(),
				longitude: geoResult.geometry.location.lng(),
				postal_code: postal_code,
				country: country,
				city: city,
				title: title
			});
			console.log('Location ok' + JSON.stringify(locationModel));
			return locationModel;
		},
		
		addMarker : function(address,title) {
			var $this = this;
			var result;
			Invitesq.geocoder.geocode({
				'address' : address
			}, function(results, status) {
				if(status == google.maps.GeocoderStatus.OK) {
					
					// Add a new marker to indicate the location
					$this.map.setCenter(results[0].geometry.location);
					var marker = new google.maps.Marker({
						map : $this.map,
						position : results[0].geometry.location
					});
					
					var locationModel = $this.createLocationModel(results[0]);
					
					// Add to collection, trigger needed editable fields for each location.
					Invitesq.locationCollection.add(locationModel);
					
				} else {
					console.log("Geocode was not successful for the following reason: " + status);
				}
			});
		},
		
		collectionChanged: function(model) {
			if (this.editable == true) {
				console.log("collection changed");
				this.appendLocation(model);
				this.$('.event-sub-title').addClass("editable");
				this.$('.event-sub-title').attr("contenteditable", "true");
			
			}
		},
		
		enableEdit: function(){
			this.$("#location-search").slideDown('slow');
			this.$('.event-sub-title').addClass("editable");
			this.$('.event-sub-title').attr("contenteditable", "true");
			
			this.editable = true;
		},
		
		disableEdit: function(){
			this.$('#location-search').slideUp('slow');
			this.$('.event-sub-title').removeClass("editable");
			this.$('.event-sub-title').removeAttr("contenteditable", "true");
			this.editable = false;
		},

		events : {
			'keyup #address' : 'getAddress',
			'click #location-add-btn' : 'btnAddress'
			//'click #location-add-btn' : 'addAddress'
		},
		
		appendLocation: function(model) {
			console.log("Append " + JSON.stringify(model));
			// Append the location to Map side bar view
			if (this.$("#event-location" )) {
				var locationView = new Invitesq.LocationView({
					model: model,
				});
				this.$("#event-location" ).append(locationView.render().el);
			}	
		},

		render : function() {
			$(this.el).html(this.template({}));
			var $this = this;
			if (Invitesq.locationCollection != -1) {
				console.log("Render locations " + Invitesq.locationCollection.length);
				Invitesq.locationCollection.each(function(location) {
					console.log("add location " + location);
					$this.appendLocation(location);
				});
			}
			
			
			return this;
		}
	});
});
